#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os

class SYSCTL(object):
    SYSPATH = "/proc/sys/"

    def __init__(self):
        """
        properties:
        {
            key: {
                path: /proc/sys/$property
                ovalue: old value
                nvalue: new value
                isset: update or not
            }
        }
        """
        self.properties = {}

    def add_property(self, key, value):
        path = os.path.join(self.SYSPATH, key.replace(".", "/"))
        curr = None
        if os.path.isfile(path):
            with open(path) as f:
                curr = f.readline().strip()

        if key in self.properties:
            self.properties[key]['nvalue'] = value
        else:
            self.properties[key] = {
                'nvalue': value,
                'isset': False,
                'path': path,
                'ovalue': curr
            }
        return self

    def apply_it(self):
        for _, v in self.properties.items():
            if v['ovalue'] != v['nvalue']:
                v['isset'] = self.set_value(v['path'], v['nvalue'])

    def restore(self):
        for _, v in self.properties.items():
            if v['isset']:
                v['isset'] = not self.set_value(v['path'], v['ovalue'])

    def set_value(self, path, value):
        with open(path, 'w') as fh:
            fh.write(value)
        return True


if __name__ == '__main__':
    sysctl = SYSCTL()
    sysctl.add_property('vm.dirty_background_ratio', '10')\
          .add_property('vm.dirty_ratio', '21')

    sysctl.apply_it()
    sysctl.restore()
